package com.library.book.servlet;

import com.alibaba.fastjson.JSON;
import com.library.book.model.Book;
import com.library.book.service.BookService;
import com.library.book.service.BookServiceImpl;
import com.library.util.PageModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(value="*.book")
public class BookServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String path = request.getServletPath();

        switch (path) {
            case "/list.book":
            case "/get.book":  // 将原有的get.book路径也映射到分页查询
            case "/available.book":  // 将原有的available.book路径也映射到分页查询，但需特殊处理
                // 分页查询
                queryByPage(request, response);
                break;
            case "/queryById.book":
                // 根据ID查询
                queryById(request, response);
                break;
            case "/addOrUpdate.book":
            case "/add.book":  // 将原有的add.book路径也映射到统一的添加/更新方法
            case "/update.book":  // 将原有的update.book路径也映射到统一的添加/更新方法
                // 添加或更新
                addOrUpdate(request, response);
                break;
            case "/deleteById.book":
            case "/delete.book":  // 将原有的delete.book路径也映射到统一的删除方法
                // 删除
                deleteById(request, response);
                break;
            case "/toEdit.book":
                // 跳转到编辑页面
                toEdit(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    /**
     * 跳转到编辑页面
     */
    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编辑标志
        request.getSession().setAttribute("saveBookFlag", 1);

        // 获取要编辑的图书ID
        String id = request.getParameter("id");

        // 跳转到编辑页面
        response.sendRedirect(request.getContextPath() + "/book_add.html?id=" + (id != null ? id : ""));
    }

    /**
     * 添加或更新图书
     */
    private void addOrUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查是否存在保存标志
        HttpSession session = request.getSession();
        Object saveFlag = session.getAttribute("saveBookFlag");

        // 获取返回页面参数
        String returnPage = request.getParameter("returnPage");
        if (returnPage == null || returnPage.isEmpty()) {
            returnPage = "book_page.html";
        }

        try {
            // 从请求参数获取图书信息
            String idStr = request.getParameter("id");
            String isbn = request.getParameter("isbn");
            String title = request.getParameter("title");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            String publishDateStr = request.getParameter("publishDate");
            String priceStr = request.getParameter("price");
            String category = request.getParameter("category");
            String status = request.getParameter("status");

            // 创建图书对象
            Book book = new Book();

            // 根据ID判断是添加还是更新
            if (idStr != null && !idStr.isEmpty()) {
                book.setId(Integer.parseInt(idStr));
            }

            book.setIsbn(isbn);
            book.setTitle(title);
            book.setAuthor(author);
            book.setPublisher(publisher);

            // 解析出版日期
            if (publishDateStr != null && !publishDateStr.isEmpty()) {
                try {
                    book.setPublishDate(sdf.parse(publishDateStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            // 解析价格
            if (priceStr != null && !priceStr.isEmpty()) {
                try {
                    book.setPrice(Integer.parseInt(priceStr));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }

            book.setCategory(category);
            book.setStatus(status != null && !status.isEmpty() ? status : "在库");

            // 执行添加或更新操作
            boolean success;
            if (book.getId() != null) {
                // 更新
                success = bookService.updateBook(book);
            } else {
                // 添加
                success = bookService.addBook(book);
            }

            // 重定向到返回页面
            if (success) {
                response.sendRedirect(request.getContextPath() + "/" + returnPage + "?message=save_success");
            } else {
                response.sendRedirect(request.getContextPath() + "/" + returnPage + "?error=save_failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/" + returnPage + "?error=exception&message=" + e.getMessage());
        } finally {
            // 清除保存标志
            session.removeAttribute("saveBookFlag");
        }
    }

    /**
     * 根据ID查询图书
     */
    private void queryById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取图书ID
        String idStr = request.getParameter("id");

        if (idStr != null && !idStr.isEmpty()) {
            try {
                Integer id = Integer.parseInt(idStr);

                // 查询图书信息
                Book book = bookService.getBookById(id);

                if (book != null) {
                    // 返回图书信息
                    out.write(JSON.toJSONString(book));
                } else {
                    Map<String, Object> result = new HashMap<>();
                    result.put("code", 404);
                    result.put("message", "图书不存在");
                    out.write(JSON.toJSONString(result));
                }
            } catch (NumberFormatException e) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 400);
                result.put("message", "无效的图书ID");
                out.write(JSON.toJSONString(result));
            }
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("message", "缺少图书ID参数");
            out.write(JSON.toJSONString(result));
        }

        out.flush();
        out.close();
    }

    /**
     * 删除图书
     */
    private void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取图书ID
        String idStr = request.getParameter("id");

        // 获取返回页面参数
        String returnPage = request.getParameter("returnPage");
        if (returnPage == null || returnPage.isEmpty()) {
            returnPage = "book_page.html";
        }

        if (idStr != null && !idStr.isEmpty()) {
            try {
                Integer id = Integer.parseInt(idStr);

                // 执行删除操作
                boolean success = bookService.deleteBook(id);

                // 重定向到返回页面
                if (success) {
                    response.sendRedirect(request.getContextPath() + "/" + returnPage + "?message=delete_success");
                } else {
                    response.sendRedirect(request.getContextPath() + "/" + returnPage + "?error=delete_failed");
                }
            } catch (NumberFormatException e) {
                response.sendRedirect(request.getContextPath() + "/" + returnPage + "?error=invalid_id");
            }
        } else {
            response.sendRedirect(request.getContextPath() + "/" + returnPage + "?error=missing_id");
        }
    }

    /**
     * 分页查询图书
     */
    private void queryByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取请求路径，用于特殊处理
        String path = request.getServletPath();

        // 获取分页参数
        String pageNoStr = request.getParameter("pageNo");
        String pageSizeStr = request.getParameter("pageSize");
        String likeValue = request.getParameter("likeValue");

        // 设置分页模型
        PageModel pageModel = new PageModel();

        // 设置当前页码
        int pageNo = 1;
        if (pageNoStr != null && !pageNoStr.isEmpty()) {
            try {
                pageNo = Integer.parseInt(pageNoStr);
            } catch (NumberFormatException e) {
                // 解析异常，使用默认值
            }
        }
        pageModel.setPageNo(pageNo);

        // 设置每页记录数
        if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
            try {
                int pageSize = Integer.parseInt(pageSizeStr);
                pageModel.setPageSize(pageSize);
            } catch (NumberFormatException e) {
                // 解析异常，使用默认值
            }
        }

        // 根据请求路径进行特殊处理
        if (path.equals("/available.book")) {
            // 设置状态为"在库"的查询条件
            likeValue = "在库";
        } else if (path.equals("/get.book")) {
            // 获取图书ID，用于查询单本图书
            String idStr = request.getParameter("id");
            if (idStr != null && !idStr.isEmpty()) {
                try {
                    Integer id = Integer.parseInt(idStr);
                    Book book = bookService.getBookById(id);

                    if (book != null) {
                        Map<String, Object> result = new HashMap<>();
                        result.put("code", 200);
                        result.put("message", "获取图书信息成功");
                        result.put("data", book);
                        out.write(JSON.toJSONString(result));
                    } else {
                        Map<String, Object> result = new HashMap<>();
                        result.put("code", 404);
                        result.put("message", "图书不存在");
                        out.write(JSON.toJSONString(result));
                    }

                    out.flush();
                    out.close();
                    return;
                } catch (NumberFormatException e) {
                    // 解析失败，继续使用普通分页查询
                }
            }
        }

        
        // 设置查询条件
        pageModel.setLikeValue(likeValue);
        
        // 执行分页查询
        List<Map<String, Object>> books = bookService.getBooksByPage(pageModel);
        
        // 设置查询结果
        pageModel.setRecordList(books);
        
        // 返回JSON结果
        if (path.equals("/available.book")) {
            // 为保持兼容，格式化为原available.book的返回格式
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "获取可借阅图书列表成功");
            result.put("data", books);
            out.write(JSON.toJSONString(result));
        } else {
            // 正常返回PageModel的JSON格式
            out.write(JSON.toJSONString(pageModel));
        }
        
        out.flush();
        out.close();
    }
}
